<template>
  <div>

    <div class="info">
      <el-row>
        <!--      <el-card class="box-card" style="width: 230px;margin-bottom: 20px" :body-style="{padding:'5px'}">-->
        <!--      </el-card>-->
        <el-col :span="17">
          <div class="warning-row-info">低危人员</div>
          <div class="danger-row-info">高危人员</div>
          <div class="ban-row-info">封禁账号</div>
        </el-col>
        <el-col :span="7">
          <div style="display:inline-block;">
            <!--            <h3  v-isAdminShow>社区</h3>-->
            <el-select v-model="value" placeholder="请选择" @change="handleSelect" style="width: 150px">
              <el-option
                v-for="item in comms"
                :key="item.cid"
                :label="item.comm_name"
                :value="item.cid">
              </el-option>
            </el-select>
            <el-input placeholder="请输入用户名" @keyup.enter.native="getUser" v-model="search_val"
                      style="width: 200px;margin-left: 10px">
            </el-input>
            <el-dropdown @command="handleRiskCommand">
              <el-button type="primary">
                导出<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="2">社区高危人员</el-dropdown-item>
                <el-dropdown-item command="1">社区低危人员</el-dropdown-item>
                <el-dropdown-item command="0">社区所有人员</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!--            <el-button @click="toExcel" type="primary">导出</el-button>-->
          </div>
        </el-col>
      </el-row>
    </div>


    <div>
      <el-table :data="tableData" style="width: 100%" border :row-class-name="tableRowClassName">
        <el-table-column
          label="用户ID"
          prop="uid">
        </el-table-column>
        <el-table-column
          label="用户社区"
          prop="comm_name">
        </el-table-column>
        <el-table-column
          label="用户名"
          prop="username">
        </el-table-column>
        <el-table-column
          label="权限"
          prop="formatted_role">
        </el-table-column>
        <el-table-column
          label="用户住址"
          prop="home_address">
        </el-table-column>
        <el-table-column
          label="联系方式"
          prop="phone">
        </el-table-column>
        <el-table-column
          label="最近登录"
          prop="login_time">
        </el-table-column>
        <el-table-column label="操作"  width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleRisk(scope.$index, scope.row)">危险
            </el-button>
            <el-button
              v-if="scope.row.enabled===true"
              size="mini"
              @click="handleAccount(scope.$index, scope.row)">封禁
            </el-button>
            <el-button
              v-if="scope.row.enabled===false"
              size="mini"
              @click="handleAccount(scope.$index, scope.row)">启用
            </el-button>
            <el-dropdown @command="handleRole" v-if="admin_user.isAdmin">
              <el-button type="primary" size="mini">
                权限<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="role in roles" :key="role.rid" :command="beforeHandleRole(role,scope.row)">
                  {{ role.nameZh }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!--            <el-button-->
            <!--              size="mini"-->
            <!--              type="danger"-->
            <!--              @click="handleDelete(scope.$index, scope.row)">删除-->
            <!--            </el-button>-->

          </template>
        </el-table-column>
      </el-table>
    </div>


    <div class="center-page">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change=getAllUser>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {Message} from "element-ui";

export default {
  name: "UserManagement",
  inject: ['reload'],

  data() {
    return {
      tableData: [],
      currentPage: 1,
      total: 0,
      pageSize: 10,


      comms: [],
      value: '所有社区',
      search_val: '',

      admin_user: {},

      roles: {},


    }
  },
  methods: {

    handleRiskCommand(command) {
      // if (command === 0) {
      //   //导出所有人员
      //   this.toExcel(0);
      // } else if (command === 1) {
      //   this.toExcel(1)
      // } else if (command === 2) {
      //   this.toExcel(2)
      // }
      this.toExcel(command)
    },

    handleRole(command) {

      console.log("uid:"+command.temp_user.uid+"  rid:"+command.role.rid)
      this.axios({
        method: "post",
        url: "/user/changeUserRoleByUid/" +command.temp_user.uid+"/"+command.role.rid ,
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            Message.success("更改成功")
            this.reload()
          }
        }
      })

    },
    beforeHandleRole(role, temp_user) {
      return {
        role: role,
        temp_user: temp_user
      }
    },


    toExcel(command) {

      if (command === '0') {
        console.log("command:" + command)
        if (this.admin_user.isAdmin) {
          if (this.value === '所有社区') {
            Message.info("请先选择社区")
          } else {
            this.axios({
              method: "get",
              url: "/excel/parseExcelByCid/" + this.value,
              responseType: 'blob'
            }).then(res => {
              if (res.data.code === 400) {
                Message.error(res.data.msg)
                return
              }
              const {data, headers} = res
              // console.log(res)
              // console.log(headers)
              let filename = decodeURI(headers["content-disposition"].replace('attachment;filename*=utf-8\'\'', ''))
              // console.log(filename)
              console.log(res.headers.get('content-type'))
              var blob = new Blob([data]); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
              // var blob = new Blob([data],{type: res.headers.get('content-type')});
              var downloadElement = document.createElement('a');
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = filename; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            })
          }
        } else {
          this.axios({
            method: "get",
            url: "/excel/parseExcelByAdmin",
            responseType: 'blob'
          }).then(res => {
            if (res.data.code === 400) {
              Message.error(res.data.msg)
              return
            }
            const {data, headers} = res
            // console.log(res)
            // console.log(headers)
            let filename = decodeURI(headers["content-disposition"].replace('attachment;filename*=utf-8\'\'', ''))
            // console.log(filename)
            console.log(res.headers.get('content-type'))
            var blob = new Blob([data]); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            // var blob = new Blob([data],{type: res.headers.get('content-type')});
            var downloadElement = document.createElement('a');
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = filename; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
          })
        }
      } else {
        // 导出危险人员
        console.log("command:" + command)
        if (this.admin_user.isAdmin) {
          if (this.value === '所有社区') {
            Message.info("请先选择社区")
          } else {
            this.axios({
              method: "get",
              url: "/excel/parseExcelByCidAndRisk/" + this.value + "/" + command,
              responseType: 'blob'
            }).then(res => {
              console.log("res" + res)
              if (res.data.code === 400) {
                Message.error(res.data.msg)
                return
              }

              const {data, headers} = res
              // console.log(res)
              // console.log(headers)
              let filename = decodeURI(headers["content-disposition"].replace('attachment;filename*=utf-8\'\'', ''))
              // console.log(filename)
              console.log(res.headers.get('content-type'))
              var blob = new Blob([data]); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
              // var blob = new Blob([data],{type: res.headers.get('content-type')});
              var downloadElement = document.createElement('a');
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = filename; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            })
          }
        } else {
          this.axios({
            method: "get",
            url: "/excel/parseExcelByAdminAndRisk" + "/" + command,
            responseType: 'blob'
          }).then(res => {
            if (res.data.code === 400) {
              Message.error(res.data.msg)
              return
            }
            const {data, headers} = res
            // console.log(res)
            // console.log(headers)
            let filename = decodeURI(headers["content-disposition"].replace('attachment;filename*=utf-8\'\'', ''))
            // console.log(filename)
            console.log(res.headers.get('content-type'))
            var blob = new Blob([data]); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
            // var blob = new Blob([data],{type: res.headers.get('content-type')});
            var downloadElement = document.createElement('a');
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = filename; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
          })
        }
      }

    },

    /*显示高危人员*/
    tableRowClassName({row, rowIndex}) {
      // console.log("@@@@@@" + row.risk)

      if (row.enabled === false) {
        return 'ban-row';
      }

      if (row.risk === 1) {
        return 'warning-row';
      } else if (row.risk === 2) {
        return 'danger-row';
      }


      return '';
    },

    handleRisk(index, row) {
      this.axios({
        method: "post",
        url: "/user/riskUserByUid/" + row.uid,
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.reload()
          }
        }
      })
    },


    handleAccount(index, row) {


      this.axios({
        method: "post",
        url: "/user/banUserById/" + row.uid,
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            if (row.enabled === true) {
              row.enabled = false;
            } else {
              row.enabled = true;
            }

            this.$message({
              message: '操作成功',
              type: 'success'
            });

          }
        }
      })

    },


    handleData(item) {
      if (item.login_time != null) {
        var date = new Date(item.login_time);
        var formatted_time = `${date.getMonth() + 1}月${date.getDate()}日${date.getHours()}时${date.getMinutes()}分`;
        item.login_time = formatted_time
      }
      var formatted_role = []
      for (var role of item.roles) {
        formatted_role.push(role.nameZh)
      }

      item.formatted_role = formatted_role.join("，")

    },


    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },

    getAllUser(currentPage) {
      this.axios({
        method: "get",
        url: "/user/getAllUsers/" + currentPage,
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            // console.log('请求成功')
            // console.log(resp.data.data)
            this.tableData = resp.data.data.records
            for (var item of this.tableData) {
              this.handleData(item)
            }
            this.currentPage = resp.data.data.current
            this.total = resp.data.data.total
            this.pageSize = resp.data.data.size
          }
        }
      })
    },


    getAllComms() {
      // this.handleCommand('all')


      //只有最高admin才可以
      this.axios({
        method: "get",
        url: "/comm/getAllComms",
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            this.comms = resp.data.data
            this.comms.unshift({comm_name: '所有社区', cid: '-1'})
            // console.log("comms" + resp.data.data)
          }
        }
      })
    },


    handleSelect() {
      // console.log(this.value)
      var cid = this.value

      if (cid == -1) {
        /*查询所有社区用户*/
        this.getAllUser(1)
      } else {
        this.axios({
          method: "get",
          url: "/user/getAllUsersByCid/" + cid + "/" + this.currentPage,
        }).then(resp => {
          if (resp) {
            if (resp.data.code == 200) {
              // console.log('请求成功')
              // console.log(resp.data.data)
              this.tableData = resp.data.data.records
              for (var item of this.tableData) {
                this.handleData(item)
              }
              this.currentPage = resp.data.data.current
              this.total = resp.data.data.total
              this.pageSize = resp.data.data.size
            }
          }
        })
      }

    },

    getUser() {
      console.log(this.search_val)

      if (this.admin_user.isAdmin) {

        if (this.search_val == null || this.search_val === '') {
          this.getAllUser()
        } else

          this.axios({
            method: "get",
            url: "/user/getUserslikeUsername/" + this.search_val + "/" + this.currentPage,
          }).then(resp => {
            if (resp) {
              if (resp.data.code == 200) {
                // console.log('请求成功')
                // console.log(resp.data.data)
                this.tableData = resp.data.data.records
                for (var item of this.tableData) {
                  this.handleData(item)
                }
                this.currentPage = resp.data.data.current
                this.total = resp.data.data.total
                this.pageSize = resp.data.data.size
              }
            }
          })
      } else {

        if (this.search_val == null || this.search_val === '') {
          this.getAllUsersByCid(this.admin_user.manageCid)
        } else

          //只能搜索本社区内的人员
          this.axios({
            method: "get",
            url: "/user/getUsersByCidlikeUsername/" + this.admin_user.manageCid + "/" + this.search_val + "/" + this.currentPage,
          }).then(resp => {
            if (resp) {
              if (resp.data.code == 200) {
                // console.log('请求成功')
                // console.log(resp.data.data)
                this.tableData = resp.data.data.records
                for (var item of this.tableData) {
                  this.handleData(item)
                }
                this.currentPage = resp.data.data.current
                this.total = resp.data.data.total
                this.pageSize = resp.data.data.size
              }
            }
          })
      }

    },


    getAllUsersByCid(cid) {
      this.axios({
        method: "get",
        url: "/user/getAllUsersByCid/" + cid + "/" + this.currentPage,
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            // console.log('请求成功')
            // console.log(resp.data.data)
            this.tableData = resp.data.data.records
            for (var item of this.tableData) {
              this.handleData(item)
            }
            this.currentPage = resp.data.data.current
            this.total = resp.data.data.total
            this.pageSize = resp.data.data.size
          }
        }
      })
    },

    getCommByCommAdmin() {
      this.axios({
        method: "get",
        url: "/comm/getCommByCommAdmin",
      }).then(resp => {
        if (resp) {
          if (resp.data.code == 200) {
            // console.log('请求成功')
            // console.log("！！！！"+resp.data.data.cid)
            this.admin_user.manageCid = resp.data.data.cid
            // console.log("！！！！     "+this.admin_user.manageCid)
            var array = new Array(resp.data.data)
            this.comms = array
            this.value = resp.data.data.comm_name
            this.getAllUsersByCid(this.admin_user.manageCid)
            return resp.data.data.cid
          }
        }
      })


    },

    getAllRoles() {
      if (this.admin_user.isAdmin) {
        this.axios({
          method: "get",
          url: "/role/getAllRoles",
        }).then(resp => {
          if (resp) {
            if (resp.data.code == 200) {
              this.roles = resp.data.data
              // console.log(resp.data.data)
            }
          }
        })

      }
    }

  },

  created() {


    this.admin_user = JSON.parse(sessionStorage.getItem("userinfo"))
    if (this.admin_user.roles.some(item => item.name === 'admin')) {
      this.admin_user.isAdmin = true
      this.getAllUser(1)
      this.getAllComms()
      this.getAllRoles()
    } else {
      /*查找当前社区管理员所管理的社区*/
      this.getCommByCommAdmin()
      this.admin_user.isAdmin = false
    }
  }

}
</script>

<style scoped>
.center-page {

  text-align: center;
  margin-top: 20px;
}

.warning-row-info {
  display: inline-block;
  background: rgba(253, 245, 230, 0.74);
  width: 100px;
  border-radius: 5px;
  font-size: small;
  font-weight: bold;
  text-align: center;
}

.danger-row-info {
  display: inline-block;
  background: rgba(248, 140, 140, 0.16);
  width: 100px;
  border-radius: 5px;
  font-size: small;
  font-weight: bold;
  text-align: center;
}

.ban-row-info {
  display: inline-block;
  background: rgba(94, 90, 90, 0.16);
  width: 100px;
  border-radius: 5px;
  font-size: small;
  font-weight: bold;
  text-align: center;
}

.info {
  /*display: inline-block;*/
  margin-bottom: 10px;
}
</style>

<style>
/*在elementUI中，row-class-name、row-style、cell-class-name等属性要想生效必须使用全局class才能生效。
因为之前的代码都是在组件中编写的，所以去除中的scoped即可该组件中的样式变为全局属性*/

.el-table .warning-row {
  background: rgba(253, 245, 230, 0.74);
}

.el-table .danger-row {
  background: rgba(248, 140, 140, 0.16);
}

.el-table .ban-row {
  background: rgba(94, 90, 90, 0.16);

}

</style>
